use askama_axum::{IntoResponse, Template};
use axum::{extract::{Path, State}, response::{Html, Redirect}, Form};
use tower_cookies::Cookies;
use tower_sessions::Session;
use crate::core::xerror::{GLOBALERROR, XErrors};
use crate::core::AppState;
use crate::types::common::Breadcrumb;
use crate::services::backend::advert_position_service::AdvertPositionService;
use crate::types::backend::advert_position_type::{AdvertPositionForm, AdvertPositionRow};
use super::{AdminSession, ErrorTemplate};

#[derive(Template)]
#[template(path = "backend/advert_position/list.html")]
struct AdvertPositionListTemplate {
    auth: AdminSession,
    breadcrumb: Breadcrumb,
    list: Vec<AdvertPositionRow>,
}


#[derive(Template)]
#[template(path = "backend/advert_position/form.html")]
struct AdvertPositionFormTemplate {
    auth: AdminSession,
    breadcrumb: Breadcrumb,
    data: AdvertPositionForm,
    url: String, // action url 
}


/// 获取所有广告位
pub async fn advert_positions_handler(State(state): State<AppState>, session: Session) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    let res = AdvertPositionService::get_all_advert_positions(&state.db).await;
    let breadcrumb = Breadcrumb {
        title: "广告位管理".to_string(),
        sub_title: "广告位列表".to_string(),
    };
   
    match res {
        Ok(list) => {
            let template = AdvertPositionListTemplate {
                auth,
                breadcrumb,
                list: list,
            };
            Html(template.render().unwrap())
        },
        Err(e) => {
            let template = ErrorTemplate {
                msg: e.to_string()
            };
            Html(template.render().unwrap())
        }
    }
   
}

/// 添加广告位表单
pub async fn add_advert_position_handler(session: Session) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    let breadcrumb = Breadcrumb {
        title: "广告位管理".to_string(),
        sub_title: "添加广告位".to_string(),
    };
    let template = AdvertPositionFormTemplate {
        auth,
        breadcrumb,
        data: AdvertPositionForm{
            name: "".to_string(), 
            flag: "".to_string()
        },
        url: "/backend/adv_position/create".to_string(),
    };
    return Html(template.render().unwrap());
}


/// 添加广告位操作
pub async fn create_advert_position_handler(
    State(state): State<AppState>, 
    cookies: Cookies,
    Form(form): Form<AdvertPositionForm>) -> Redirect {
    let error = XErrors::new();
    if form.name.is_empty() {
        error.set_cookie_error(cookies, GLOBALERROR::PARAMINVALIDFAILED, "".to_string());
        return Redirect::to("/backend/adv_position/create");
    }
    let res = AdvertPositionService::insert_advert_position(&state.db, &form).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::ADDSUCCESS, "".to_string());
            return Redirect::to("/backend/adv_position/list");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::ADDSUCCESS, db_error);
            return Redirect::to("/backend/adv_position/list");
        }
    }
}

/// 修改广告位表单
pub async fn edit_advert_position_handler(State(state): State<AppState>, session: Session, Path(id): Path<i64>) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    let res = AdvertPositionService::get_advert_position_by_id(&state.db, id).await;
    let breadcrumb = Breadcrumb {
        title: "广告位管理".to_string(),
        sub_title: "修改广告位".to_string(),
    };
    match res {
        Ok(data) => {
            let template = AdvertPositionFormTemplate {
                auth,
                breadcrumb,
                data,
                url: format!("/backend/adv_position/edit/{}", id),   
            };
            return Html(template.render().unwrap());
        },
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string(),
            };
            return Html(template.render().unwrap());
        }
    }
}

/// 修改广告位操作
pub async fn update_advert_position_handler(
    State(state): State<AppState>, 
    cookies: Cookies, 
    Path(id): Path<i64>,
    Form(form): Form<AdvertPositionForm>) -> Redirect {
    let error = XErrors::new();
    // 名称不能为空
    if form.name.is_empty() {
        error.set_cookie_error(cookies, GLOBALERROR::PARAMINVALIDFAILED, "".to_string());
        return Redirect::to(format!("/backend/adv_position/edit/{}", id).as_str());
    }

    let res = AdvertPositionService::update_advert_position(&state.db, id, &form).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::UPDATESUCCESS, "".to_string());
            return Redirect::to("/backend/adv_position/list");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::UPDATEFAILED, db_error);
            return Redirect::to("/backend/adv_position/list");
        }
    }
}

/// 删除广告位操作
pub async fn delete_advert_position_handler(
    State(state): State<AppState>, 
    cookies: Cookies,
    Path(id): Path<i64>) -> Redirect {
    let error = XErrors::new();
    // 是否存在
    let exist = AdvertPositionService::exist_advert_position_by_id(&state.db, id).await;
    let total = match exist {
        Ok(total) => total,
        Err(_) => 0,
    };
    if total == 0 {
        error.set_cookie_error(cookies, GLOBALERROR::RECORDNOTFOUND, "".to_string());
        return Redirect::to("/backend/adv_position/list");
    }
    let res = AdvertPositionService::delete_advert_position(&state.db, id).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::DELETESUCCESS, "".to_string());
            return Redirect::to("/backend/adv_position/list");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::DELETEFAILED, db_error);
            return Redirect::to("/backend/adv_position/list");
        }
    }
}